//
//  ComposeViewController.swift
//  Weibo10
//
//  Created by male on 15/10/24.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD
// MARK: - 撰写控制器
class ComposeViewController: UIViewController {
    
    private lazy var picturePickerController:PicturePickerController = PicturePickerController()
    // MARK: - 监听方法
    /// 关闭
    @objc private func close() {
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发布微博
    @objc private func sendStatus() {
        print("发布微博")
        let text = textView.emoticonText
        let image = picturePickerController.pictures.last
        NetWorkTools.sharedTools.sendStatus(text ,image:image) { (result, error) -> () in
            if error != nil{
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }
            else{
                self.close()
            }
        }
    }
    @objc private func keyboardChanged(n:NSNotification){
        print(n.userInfo)
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let duration = (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as!
            NSNumber).doubleValue
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        let offSet = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        toolbar.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(view.snp_bottom).offset(offSet)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
             self.view.layoutIfNeeded()
        }
       
       
    }
    /// 选择照片
    @objc private func selectPicture() {
        textView.resignFirstResponder()
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(picturePickerController.view.snp_top)
        }
        picturePickerController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.size.height * 0.6)

        }
    }
    /// 选择表情
    @objc private func selectEmoticon() {
        print("选择表情")
        //先注销键盘
        textView.resignFirstResponder()
        
        textView.inputView = textView.inputView == nil ? emoticonView:nil
        
        textView.becomeFirstResponder()
    }

    // MARK: - 视图生命周期
    override func loadView() {
        view = UIView()
        
        setupUI()
    }
    override func viewDidLoad() {
        print("执行viewDidLoad")
        super.viewDidLoad()
        textView.delegate = self
        textView.becomeFirstResponder()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name:UIKeyboardWillChangeFrameNotification , object: nil)
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
//    override func viewDidAppear(animated: Bool) {
//        super.viewDidAppear(animated)
//        print("执行viewDidAppear")
//
//    }
    // MARK: - 懒加载控件
    private lazy var emoticonView:EmoticonView = EmoticonView { [weak self](emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }
    /// 工具条
    private lazy var toolbar = UIToolbar()
    private lazy var textView:UITextView = {
        let textView = UITextView()
        textView.font = UIFont.systemFontOfSize(18)
        textView.textColor = UIColor.darkGrayColor()
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return textView
    }()
    /// 占位标签
    private lazy var placeHolderLabel: UILabel = UILabel(title: "说点什么",
        fontSize: 18,
        color: UIColor.lightGrayColor())

}
// MARK: - UITextViewDelegate
extension ComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView){
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
    }
}

// MARK: - 设置界面
private extension ComposeViewController {
    
    func setupUI() {
        //取消自动调整滚动视图间距
        automaticallyAdjustsScrollViewInsets = false

        // 1. 设置背景颜色
        view.backgroundColor = UIColor.whiteColor()

        // 2. 设置控件
        prepareNavigationBar()
        prepareToolbar()
        prepareTextView()
        preparePicturePicker()
    }
    /// 准备照片选择控制器
    private func preparePicturePicker() {
        
        // 0. 添加子控制器
        addChildViewController(picturePickerController)
        
        // 1. 添加视图
        view.insertSubview(picturePickerController.view, belowSubview: toolbar)
        
        // 2. 自动布局
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(0)
        }
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }

    //准备textView
    private func prepareTextView(){
       view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolbar.snp_top)
        }
        

        // 添加占位标签
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }

    }
    /// 准备工具条
    private func prepareToolbar() {
        // 1. 添加控件
        view.addSubview(toolbar)
        // 设置背景颜色
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        // 2. 自动布局
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
        
        // 3. 添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture", "actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            items.append(UIBarButtonItem(imageName: dict["imageName"]!,
                target: self,
                actionName: dict["actionName"]))
            
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        // 一旦复制，相当于做了一次copy
        toolbar.items = items
    }
    
    /// 设置导航栏
    private func prepareNavigationBar() {
        
        // 1. 左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        // 2. 标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        navigationItem.titleView = titleView
        
        // 3. 添加子控件
        let titleLabel = UILabel(title: "发微博", fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.account?.screen_name ?? "",
            fontSize: 13,
            color: UIColor.lightGrayColor())
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
    }
}